package cn.tedu.csmall.stock.webapi.controller;

import cn.tedu.csmall.commons.exception.CoolSharkServiceException;
import cn.tedu.csmall.commons.pojo.stock.dto.StockReduceCountDTO;
import cn.tedu.csmall.commons.restful.JsonResult;
import cn.tedu.csmall.commons.restful.ResponseCode;
import cn.tedu.csmall.stock.service.IStockService;
import cn.tedu.csmall.stock.webapi.exception.StockBlockError;
import cn.tedu.csmall.stock.webapi.exception.StockFallbackError;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/base/stock")
@Api(tags = "库存管理")
public class StockController {
    @Autowired
    private IStockService stockService;

    @PostMapping("/reduce/count")
    @ApiOperation("减少指定商品的库存")
    //在@SentinelResource注解中，添加一个blockHandler的属性，该属性指定的就是限流方法名
    //fallback属性指定降级方法名
    //blockHandlerClass指定的是限流的类
    @SentinelResource(value = "减少库存的方法",blockHandlerClass = StockBlockError.class,
            blockHandler = "blockError",
            fallbackClass = StockFallbackError.class,fallback = "fallbackError")
    public JsonResult reduceCountByCommodityCode(StockReduceCountDTO stockReduceCountDTO){
        //百分之60的概率，抛出异常
        if(Math.random()<0.6){
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"抛出随机异常");
        }
        stockService.reduceCountByCommodityCode(stockReduceCountDTO);
        return JsonResult.ok("商品库存减少完成！！");
    }
    //自定义限流方法
    //1.访问修饰符是public
    //2.返回值类型必须和限流的控制层方法一致
    //3.方法名称要和@SentinelResource注解中的blockHandler一致
    //4.方法参数列表必须和被限流控制层方法一致，而且需要添加一个BlockException类型的参数
//    public JsonResult blockError(StockReduceCountDTO stockReduceCountDTO,
//                                 BlockException e){
//        //限流方法一般直接返回限流信息就可以了
//        return JsonResult.failed(ResponseCode.BAD_REQUEST,"服务器繁忙，请稍后重试~");
//    }
    //自定义降级方法
    //降级方法的返回值类型要和原始方法一致
    //降级方法的参数列表要和原始方法一致，还可以传入异常的参数类型
//    public JsonResult fallbackError(StockReduceCountDTO stockReduceCountDTO){
//        return JsonResult.failed(ResponseCode.BAD_REQUEST,"运行方法失败，服务降级");
//    }
}
